package br.unesp.demac.bcc.soo.clarus.view;

import br.unesp.demac.bcc.soo.clarus.bean.Localizacao;
import br.unesp.demac.bcc.soo.clarus.bean.Obra;
import br.unesp.demac.bcc.soo.clarus.dao.LocalizacaoDAO;
import br.unesp.demac.bcc.soo.clarus.dao.LocalizacaoDAOImp;
import br.unesp.demac.bcc.soo.clarus.dao.ObraDAO;
import br.unesp.demac.bcc.soo.clarus.dao.ObraDAOImp;
import br.unesp.demac.bcc.soo.clarus.util.FrameUtil;
import java.awt.Rectangle;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Evaldo
 */
public class JFrameAlterarObra extends javax.swing.JFrame {

    private List<Obra> lstObra = new ArrayList<Obra>();
    private Obra obrSelecionada = new Obra();
    
    /** Creates new form JFrameAlterarObra */
    public JFrameAlterarObra() {
        initComponents();        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        lblAlterarObra = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        lblNomeObra = new javax.swing.JLabel();
        txtNomeObra = new javax.swing.JTextField();
        btnPesquisar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPesqObras = new javax.swing.JTable();
        lblNmObra = new javax.swing.JLabel();
        lblExibirObra = new javax.swing.JLabel();
        lblAnoPublicacao = new javax.swing.JLabel();
        lblExibirAnoPublicacao = new javax.swing.JLabel();
        lblLocalizacao = new javax.swing.JLabel();
        cbxLocalizacao = new javax.swing.JComboBox();
        LocalizacaoDAO locDao = new LocalizacaoDAOImp();
        List<Localizacao> lstLoc = locDao.buscaTodasLocalizacoes();

        for (Localizacao loc : lstLoc)
        cbxLocalizacao.addItem(loc.toString());
        btnExcluir = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        btnEditar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Alterar Obra");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        lblAlterarObra.setFont(new java.awt.Font("Calibri", 1, 18));
        lblAlterarObra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/icon_livro.gif"))); // NOI18N
        lblAlterarObra.setText("Alterar Obra");

        lblNomeObra.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblNomeObra.setText("Nome da Obra:");

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        tblPesqObras.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome da Obra", "Ano de Publicação", "Localização"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblPesqObras.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblPesqObras);

        lblNmObra.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblNmObra.setText("Nome da Obra:");

        lblExibirObra.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblExibirObra.setText("jLabel2");

        lblAnoPublicacao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblAnoPublicacao.setText("Ano de Publicação:");

        lblExibirAnoPublicacao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblExibirAnoPublicacao.setText("jLabel3");

        lblLocalizacao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblLocalizacao.setText("Localização:");

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(lblAlterarObra))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(lblNomeObra)
                        .addGap(10, 10, 10)
                        .addComponent(txtNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(435, 435, 435)
                        .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(15, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblNmObra)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblAnoPublicacao)
                                    .addComponent(lblLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(27, 27, 27)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblExibirObra, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(lblExibirAnoPublicacao, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                                        .addGap(40, 40, 40))
                                    .addComponent(cbxLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(271, Short.MAX_VALUE)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(lblAlterarObra)
                .addGap(11, 11, 11)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(lblNomeObra))
                    .addComponent(txtNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnPesquisar)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(btnEditar)
                .addGap(41, 41, 41)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblNmObra)
                    .addComponent(lblExibirObra))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblAnoPublicacao)
                    .addComponent(lblExibirAnoPublicacao))
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLocalizacao)
                    .addComponent(cbxLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(52, 52, 52)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalvar)
                    .addComponent(btnExcluir)
                    .addComponent(btnCancelar))
                .addContainerGap(23, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        try{
            ObraDAO obrDao = new ObraDAOImp();
            lstObra = obrDao.buscarObrasLocalizacao(txtNomeObra.getText().trim());
            
            if (lstObra.size() > 0){
                DefaultTableModel model = (DefaultTableModel)tblPesqObras.getModel();
                model.setNumRows(0);
                for (Obra obr : lstObra)
                    model.addRow(new String[] { obr.getNomeObra(), String.valueOf(obr.getAnoPublicacao()), 
                        obr.getLocalizacao().toString(), String.valueOf(obr.getIdObra()) } );
            }
            else{
                JOptionPane.showMessageDialog(this, "A pesquisa não encontrou resultados.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        catch(SQLException ex){
            JOptionPane.showMessageDialog(this, "Erro ao consultar: " + ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        int index = tblPesqObras.getSelectedRow();
        
        if (index != - 1){
            obrSelecionada = lstObra.get(index);
            
            lblExibirObra.setText(obrSelecionada.getNomeObra());
            lblExibirAnoPublicacao.setText(String.valueOf(obrSelecionada.getAnoPublicacao()));
            cbxLocalizacao.setSelectedItem(obrSelecionada.getLocalizacao().toString());                      
            
            //Rectangle rect = new Rectangle(560, 590);
            //this.setBounds(rect);
            this.setSize(560, 590);
            //FrameUtil.centralizar(this);
        }
        else{
            JOptionPane.showMessageDialog(this, "Selecione uma obra para edição.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
        
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        int option = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir a obra?", "Aviso", JOptionPane.YES_NO_OPTION);
        
        if (option == 0){
            obrSelecionada.setFlagExcluido(true);
            ObraDAO obrDao = new ObraDAOImp();
            obrDao.atualizarObra(obrSelecionada);
        }
        
        resetarTela();
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        String[] dadosLocal = cbxLocalizacao.getSelectedItem().toString().split("-");
        LocalizacaoDAO locDao = new LocalizacaoDAOImp();
        Localizacao loc = locDao.getLocalizacao(dadosLocal[0], dadosLocal[1]);
        obrSelecionada.setLocalizacao(loc);
        
        ObraDAO obrDao = new ObraDAOImp();
        obrDao.atualizarObra(obrSelecionada);
        
        resetarTela();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        //Rectangle rect = new Rectangle(560, 350);
        //this.setBounds(rect);
        this.setSize(560,350);
        FrameUtil.centralizar(this);
    }//GEN-LAST:event_formWindowOpened

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        resetarTela();
    }//GEN-LAST:event_btnCancelarActionPerformed

    /**
     * Reseta os itens da tela para o modo inicial
     */
    private void resetarTela(){
        DefaultTableModel model = (DefaultTableModel)tblPesqObras.getModel();
        int size = model.getRowCount() - 1;
        for (int i = size; i >= 0; i--)
            model.removeRow(i);        
        
        //Rectangle rect = new Rectangle(560, 350);
        //this.setBounds(rect);
        //FrameUtil.centralizar(this);
        this.setSize(560,350);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameAlterarObra().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbxLocalizacao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblAlterarObra;
    private javax.swing.JLabel lblAnoPublicacao;
    private javax.swing.JLabel lblExibirAnoPublicacao;
    private javax.swing.JLabel lblExibirObra;
    private javax.swing.JLabel lblLocalizacao;
    private javax.swing.JLabel lblNmObra;
    private javax.swing.JLabel lblNomeObra;
    private javax.swing.JTable tblPesqObras;
    private javax.swing.JTextField txtNomeObra;
    // End of variables declaration//GEN-END:variables
}
